package com.example.app.moudle.home.adapter.vh.base

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.LogUtils
import com.chad.library.adapter4.BaseMultiItemAdapter
import com.chad.library.adapter4.util.addOnDebouncedChildClick
import com.chad.library.adapter4.util.setOnDebouncedItemClick
import com.example.app.R
import com.example.app.databinding.LayoutHomeRecommendBinding
import com.example.app.manager.StateViewManager
import com.example.app.moudle.home.HomeF
import com.example.app.moudle.home.adapter.HomeRecommendAdapter
import com.example.app.moudle.home.entity.HomeTabEntity
import com.example.app.moudle.home.event.EventHomeLoadMore
import com.example.app.moudle.home.event.EventHomeRefresh
import com.example.app.moudle.home.vm.HomeVM
import com.libcommon.LiveEventManager
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener

/**
 * CreateBy:Joker
 * CreateTime:2024/1/8 20:01
 * description：
 */
class VHRecommendPage(
    parent: ViewGroup,
    val binding: LayoutHomeRecommendBinding = LayoutHomeRecommendBinding.inflate(LayoutInflater.from(parent.context), parent, false)
) : RecyclerView.ViewHolder(binding.root)

abstract class BaseHomePageAdapter(val homeF: HomeF) : BaseMultiItemAdapter.OnMultiItemAdapterListener<HomeTabEntity, VHRecommendPage> {

    abstract fun onRefreshList()

    abstract fun onLoadMoreList()

    protected val TAG = javaClass.simpleName
    protected val mapAdapter by lazy { mutableMapOf<Int, HomeRecommendAdapter>() }

    override fun onCreate(context: Context, parent: ViewGroup, viewType: Int) = VHRecommendPage(parent)

    override fun onBind(holder: VHRecommendPage, position: Int, item: HomeTabEntity?) {
        if (item == null) return

        holder.binding.apply {
            val homeRecommendAdapter = HomeRecommendAdapter()
            mapAdapter[item.tabId] = homeRecommendAdapter

            val stateView = StateViewManager.inject(flContent).apply {
                setEmptyResId(R.layout.app_state_view_empty)
                showLoading()
            }

            initRefresh(srlRecommend)
            initRecycleView(rvRecommend, homeRecommendAdapter)
            initAdapterClick(homeRecommendAdapter)

            //刷新数据
            LiveEventManager.observe(homeF.viewLifecycleOwner, EventHomeRefresh::class.java) {
                LogUtils.i("$TAG 刷新列表 size=${it.entity.size} hasMore=${it.hasMore} from=${it.pageType}")
                if (it.pageType != item.tabId) return@observe

                srlRecommend.apply {
                    setEnableRefresh(true)
                    finishRefresh()
                    setEnableLoadMore(it.hasMore)
                }

                if (it.entity.isEmpty()) {
                    homeRecommendAdapter.submitList(mutableListOf())
                    stateView.showEmpty()
                } else {
                    homeRecommendAdapter.submitList(it.entity)
                    stateView.showContent()
                }
            }

            //加载更多
            LiveEventManager.observe(homeF.viewLifecycleOwner, EventHomeLoadMore::class.java) {
                LogUtils.i("$TAG 加载更多 size=${it.entity.size} hasMore=${it.hasMore} from=${it.pageType}")
                if (it.pageType != item.tabId) return@observe

                if (it.entity.isNotEmpty()) {
                    homeRecommendAdapter.addAll(it.entity)
                }
                srlRecommend.apply {
                    finishLoadMore()
                    setEnableLoadMore(it.hasMore)
                }
            }

            onRefreshList()
        }
    }

    private fun initRefresh(smartRefreshLayout: SmartRefreshLayout) {
        smartRefreshLayout.apply {
            setEnableAutoLoadMore(false)
            setEnableLoadMore(false)
            setEnableRefresh(false)
        }

        smartRefreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                LogUtils.i("$TAG onRefresh")
                onRefreshList()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                LogUtils.i("$TAG onLoadMore ")
                onLoadMoreList()
            }
        })
    }

    private fun initRecycleView(recyclerView: RecyclerView, recommendAdapter: HomeRecommendAdapter) {
        recyclerView.apply {
            layoutManager = GridLayoutManager(context,2)
            adapter = recommendAdapter
            setHasFixedSize(true)
            recommendAdapter.onAttachedToRecyclerView(this)
        }

        //初始化曝光
//        val rvExposeManager = RecycleViewExposeManager()
        // val exposeAnchorUid = mutableListOf<Int>()

        //initListExpose(rvExposeManager, exposeAnchorUid, recyclerView, recommendAdapter)

        //定时更新主播在线状态
//        LiveEventManager.observe(messageF.viewLifecycleOwner, EventUpdateOnlineStatus::class.java) {
//            if (messageF.currentPage == itemViewType && messageF.isVisible) {
//                rvExposeManager.handleCurrentVisibleItems()
//            }
//        }
    }

//    private fun initListExpose(exposeManager: RecycleViewExposeManager, exposeAnchorUid: MutableList<Int>, rvMessage: RecyclerView, recommendAdapter: HomeRecommendAdapter) {
//        exposeManager.setRecyclerItemExposeListener(recyclerView = rvMessage, onListExpose = { firstPos, lastPos ->
//            if (messageF.currentPage == itemViewType && messageF.isVisible) {
//                exposeAnchorUid.clear()
//
//                //获取已经曝光的
//                for (i in firstPos..lastPos) {
//                    if (recommendAdapter.items.size > i) {
//                        val uid = recommendAdapter.getItem(i).targetUid
//                        if (!exposeAnchorUid.contains(uid)) exposeAnchorUid.add(uid)
//                    }
//                }
//
//                //获得的曝光数
//                LogUtils.i("$TAG initListExpose itemViewType=$itemViewType firstPos=$firstPos lastPos=$lastPos exposeAnchorUid=${exposeAnchorUid.size}")
//
//                if (exposeAnchorUid.isNotEmpty()) {
//                    TimerTaskManager.reqUpdateOnlineStatus(messageF.viewLifecycleOwner, exposeAnchorUid) {
//                        if (!it.isNullOrEmpty() && messageF.currentPage == itemViewType && messageF.isVisible) {
//                            LogUtils.i("$TAG OnlineStatus Update anchorList=$it itemViewType=$itemViewType")
//
//                            it.forEach { bean ->
//                                recommendAdapter.data.forEachIndexed { index, anchorItemBean ->
//                                    //在线状态变化了
//                                    if (bean.UID == anchorItemBean.targetUid) {
//                                        anchorItemBean.onlineStatus = bean.ApStatus
//                                        recommendAdapter.getViewByPosition(index, R.id.viewStatus)?.let { viewStatus ->
//                                            AppHelp.setOnlineStatus(onlineStatus = bean.ApStatus, viewStatus = viewStatus)
//                                        }
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//        })
//    }

    private fun initAdapterClick(recommendAdapter: HomeRecommendAdapter) {
        recommendAdapter.apply {
            //每一项Item点击
            setOnDebouncedItemClick { _, _, position ->
                if (items.size > position) {
                    val itemData = items[position]
                    LogUtils.i("$TAG itemClick position=${position}")

                }
            }

            //子项点击
            addOnDebouncedChildClick(R.id.ivBg) { _, _, position ->
                if (items.size > position) {
                    val itemData = items[position]
                    LogUtils.i("$TAG itemChildClick position=${position}")

                }
            }
        }
    }

}